package net.lbtech.util;

import com.alibaba.fastjson.JSONObject;
import net.lbtech.util.exception.IpException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 百度API接口
 * Created by Administrator on 2016/11/22 0022.
 */
public class IPUtil {
    protected static Logger logger = LoggerFactory.getLogger(IPUtil.class);

    /**
     * 根据IP获取地址详细数据
     * @param ip
     * @return
     * @throws IpException
     */
    public static JSONObject getAdderss(String ip) throws IpException {
        HashMap map = new HashMap();
        map.put("ip",ip);
        map.put("ak","zbPOysaUWHbmm6lUbDEqkGpMetBcDHgp");
        JSONObject adderss = HttpUtil.postAsJson(map,"http://api.map.baidu.com/location/ip");
        logger.debug(adderss.toJSONString());
        int status = adderss.getIntValue("status");
        if(status!=0){
            throw new IpException(adderss.toJSONString());
        }
        return adderss;
    }

    /**
     * 根据IP获取到市
     * @param ip
     * @return
     * @throws IpException
     */
    public static String getCity(String ip) throws IpException {
        JSONObject adderss = getAdderss(ip);
        String ctiy = adderss.getJSONObject("content")
                .getJSONObject("address_detail")
                .getString("city");
        return ctiy;
    }

    /**
     * 获取城市没有后缀名
     * @param ip
     * @return
     * @throws IpException
     */
    public static String getCityNoSuffix(String ip) throws IpException {
        String address = "";
        try {

            //获取返回的Json
            JSONObject ref = IPUtil.getAdderss("63.149.98.23");
            String addressList = ref.getString("address");
            //切割
            String[] addressArray = StringUtils.split(addressList,"|");
            if (!"None".equals(addressArray[2]) ){
                address = addressArray[2];
            }else {
                address = addressArray[1];
            }
            logger.debug(address);
        } catch (IpException e) {
            logger.error("IP错误",e);
        } catch (Exception e){
            logger.error("意外错误",e);
        }
        return address;
    }


}